package com.lincoln.util;

/**
 * 生成payload
 * payload格式[参数数量4位][第一个参数长度4位][第一个参数内容][第二个参数长度][第二个参数内容]
 */
public class PayloadUtil {
    /**
     * 根据参数列表生成payload
     *
     * @param params
     * @return
     */
    public static byte[] generatePayload(byte[]... params) {
        int length = params.length;
        if (params.length == 1 && params[0].length == 0) {
            length = 0;
        }
        int size = 4 + length * 4;
        for (int i = 0; i < length; i++) {
            size += params[i].length;
        }
        byte[] lengthByte = ByteUtil.int2byte(length);
        byte[] res = new byte[size];
        int index = 0;

        for (byte b : lengthByte) {
            res[index] = b;
            index++;
        }

        for (int i = 0; i < length; i++) {
            byte[] param = params[i];
            byte[] paramLengthByte = ByteUtil.int2byte(param.length);
            for (byte b : paramLengthByte) {
                res[index] = b;
                index++;
            }
            for (byte b : param) {
                res[index] = b;
                index++;
            }
        }
        return res;
    }

    /**
     * 解析payload
     *
     * @param payload
     * @return
     */
    public static byte[][] resolvePayload(byte[] payload) {
        if (payload.length < 4) {
            return new byte[0][0];
        }
        // 参数个数
        byte[] lengthByte = ByteUtil.sub(payload, 0, 4);
        int length = ByteUtil.byte2int(lengthByte);
        int index = 4;
        byte[][] res = new byte[length][];
        for (int i = 0; i < length; i++) {
            byte[] paramLengthByte = ByteUtil.sub(payload, index, index + 4);
            int paramLength = ByteUtil.byte2int(paramLengthByte);
            index += 4;
            byte[] param = new byte[paramLength];
            for (int j = 0; j < paramLength; j++) {
                param[j] = payload[index];
                index++;
            }
            res[i] = param;
        }
        return res;
    }

    public static void main(String[] args) {
        byte[] res = generatePayload(ByteUtil.int2byte(3000),ByteUtil.int2byte(0));
        System.out.println("11111");
    }
}
